package edu.rit.hvz.android;

import edu.rit.hvz.android.DataLayer.MissionDBAdapter;
import edu.rit.hvz.android.DataLayer.NewsDBAdapter;
import edu.rit.hvz.android.DataLayer.ServerDatabaseConnection;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class EditEvent extends Activity implements  OnClickListener{
	private EditText title;
	private EditText content;
	private Cursor event;
	private NewsDBAdapter db;	
	private long id;
	
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Utils.onActivityCreateSetTheme(this);
		setContentView(R.layout.edit_layout);

		Button mybutton = (Button)findViewById(R.id.button1);
		mybutton.setText(R.string.post);
		findViewById(R.id.button1).setOnClickListener(this);
		
		db = new NewsDBAdapter(this);
        db.open();
        
        title = (EditText)findViewById(R.id.textView1);
        content = (EditText)findViewById(R.id.textView2);
		
		id = this.getIntent().getLongExtra(MissionDBAdapter.ROW_ID, -1);
		if( id != -1 ){
			event = db.getNews(id);
			title.setText(event.getString(event.getColumnIndex(NewsDBAdapter.TITLE)));
			content.setText(event.getString(event.getColumnIndex(NewsDBAdapter.CONTENT)));
			mybutton.setText(R.string.submit_change);
		}
		db.close();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater mInflater = getMenuInflater();
		mInflater.inflate(R.layout.menu, menu);
        return super.onCreateOptionsMenu(menu);
        
    }
	
	 @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	    	case R.id.settings:
				this.startActivity(new Intent(this, Preferences.class));
				return true;
	        }
	        return false;
	    }
    
	public void onClick(View v) {
		if(id != -1){
			db.open();
			db.updateNewsServer(id, title.getText().toString(), content.getText().toString(), true);
			db.close();
		} else {
			db.open();
			long newID = db.createNewsServer(title.getText().toString(), content.getText().toString(), true);
			ServerDatabaseConnection.populateNews(this);
			db.close();
			
			Intent intent = new Intent().setClass(this, Event.class);
			intent.putExtra(NewsDBAdapter.ROW_ID, newID);
			this.startActivity(intent);	
		}
		
		this.finish();
		//this.startActivity(new Intent(this, Event.class));
	}
	

}
